package murraco.service.impl;

import murraco.common.ResultCode;
import murraco.constants.BicycleConstants;
import murraco.dto.BicycleNumDto;
import murraco.exception.BusinessException;
import murraco.model.Bicycle;
import murraco.model.Record;
import murraco.repository.BicycleRepository;
import murraco.service.BicycleService;
import murraco.service.PileService;
import murraco.service.RecordService;
import murraco.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

@Service
public class BicycleServiceImpl implements BicycleService {


    private final BicycleRepository bicycleRepository;

    private final RecordService recordService;

    private final PileService pileService;

    private final UserService userService;


    @Autowired
    public BicycleServiceImpl(BicycleRepository bicycleRepository, RecordService recordService, PileService pileService, UserService userService) {
        this.bicycleRepository = bicycleRepository;
        this.recordService = recordService;
        this.pileService = pileService;
        this.userService = userService;
    }

    @Override
    public BicycleNumDto borrowBicycle(String pileNum,String userId) {

        Bicycle bicycle = bicycleRepository.findByPileNum(pileNum).orElseThrow(()->new BusinessException(ResultCode.RESULT_DATA_NONE));

        Record record = recordService.addRecord(bicycle.getBicycleNum(),bicycle.getPileNum(),userId);

        bicycle.setBicycleStatus(BicycleConstants.borrowed);
        bicycle.setRecordId(record.getId());
        bicycle.setPileNum("");
        bicycleRepository.save(bicycle);

        String[] num = pileNum.split("\\+");
        pileService.outPile(num[0]);
        userService.borrowBicycle(userId,bicycle.getBicycleNum());

        BicycleNumDto bicycleNumDto = new BicycleNumDto();
        bicycleNumDto.setBicycleNum(bicycle.getBicycleNum());

        return bicycleNumDto;
    }

    @Override
    public void returnBicycle(String bicycleNum,String pileNum,String userId) {

        this.checkIfHasCar(pileNum);
        Bicycle bicycle = bicycleRepository.findByBicycleNum(bicycleNum).orElseThrow(() -> new BusinessException(ResultCode.DATA_IS_WRONG));
        bicycle.setBicycleStatus(BicycleConstants.unBorrowed);
        bicycle.setPileNum(pileNum);

        recordService.updateRecord(bicycle.getRecordId());
        bicycleRepository.save(bicycle);

        String[] num = pileNum.split("\\+");
        pileService.inPile(num[0]);
        userService.returnBicycle(userId);
    }

    private void checkIfHasCar(String pileNum){
        Bicycle bicycle = bicycleRepository.findByPileNum(pileNum).orElse(null);
        if(!ObjectUtils.isEmpty(bicycle)){
            throw new BusinessException(ResultCode.HAS_CAR);
        }
    }

}

